import React, { PureComponent } from 'react'
import { Card, WingBlank, WhiteSpace } from 'antd-mobile'
import MenuBar from '@/components/MenuBar'
import LoadMore from '@/components/LoadMore'
import Cover from '@/components/Cover'
import config from '@/router/config'
import { channelApi } from '@/api'
import css from './index.module.scss'
export default class Channel extends PureComponent {
    constructor(props) {
        super(props)
        this.state = this.initState()
    }

    listRef = React.createRef()

    // 渲染前获取路由参数修改state
    initState = () => {         
        const { currentTab, tabs, childId } = this.getCurrentTab()
        let isChannelIndex = currentTab === 0
        let modules = []           
        if (isChannelIndex) {
            modules = tabs.map(menu => {
                return {
                    title: menu.name === '推荐' ? '热门推荐' : menu.name,
                    tid: menu.tid,
                    data: []
                }
            })
        } else {
            modules = [
                {
                    title: '热门推荐',
                    tid: childId,
                    data: []
                },
                {
                    title: '最新视频',
                    tid: childId,
                    data: []
                }
            ]
        }
        return {
            currentTab,
            tabs,
            currentModules: [],
            isChannelIndex,
            modules,
            currentPage: 1,
            totalPage: null
        }
    }

    // 处理菜单栏点击
    handleTab = tab => {
        const { tid } = tab
        const { match: { params: { id } }, history } = this.props    
        history.push(`/channel/${id}${tid !== (id - 0) ? ('/'+tid) : ''}`)    
    }
    
    // 检测url参数是否有效
    checkUrl = () => {
        let flag = true
        const { match: { params } } = this.props
        let id
        let childId
        if (params) {
            id = params.id
            childId = params.childId
            id = id - 0            
            const parent = config.find(item => item.tid === id && !item.hide)
            if (!parent) {
                flag = false
            } else {
                const { sub } = parent
                if (childId && Array.isArray(sub)) {
                    childId = childId - 0
                    const matchIndex = sub.findIndex(item => item.tid === childId && !item.hide)
                    flag = matchIndex > -1
                }
            }
        }
        return flag
    }

    // 获取当前菜单栏索引以及下面的子模块
    getCurrentTab = () => {
        let currentTab = 0
        let tabs = []
        const { match: { params } } = this.props
        let id
        let childId
        if (params) {
            id = params.id
            childId = params.childId
            id = id - 0            
            const parent = config.find(item => item.tid === id && !item.hide)
            if (!parent) {
                return {}
            }
            const { sub } = parent
            tabs = [{
                name: '推荐',
                tid: id
            }, ...sub]                             
            if (childId && Array.isArray(sub)) {
                childId = childId - 0
                currentTab = sub.findIndex(item => item.tid === childId && !item.hide)
                currentTab = currentTab < 0 ? 0 : (currentTab + 1)                   
            }              
        }
        return {
            tabs,
            currentTab: currentTab,
            id,
            childId
        }
    }

    initData = () => {
        const { isChannelIndex } = this.state
        if (isChannelIndex) {
            this.initRecommend()
        } else {
            this.initChannel()
        }
    }

    // 页面初始化获取频道推荐数据
    initRecommend = async () => {
        const { tabs, modules } = this.state
        const initLoadTabs = tabs.slice(0, 3)
        const results = initLoadTabs.map(async tab => {
            const response = await channelApi.getRecommend({
                rid: tab.tid
            })
            return response
        })

        // 按次序输出
        let currentModules = []
        for (const [index, result] of results.entries()) {
            const res = await result
            let cm = {
                title: modules[index].title,
                tid: modules[index].tid,
                data: null
            }
            if (res) {
                const { code, data } = res
                if (code === 0 && data) {
                    cm.data = data.slice(0, 4)                    
                }
            } 
            currentModules.push(cm)
        }

        this.setState({
            currentModules,
            currentPage: 2,
            totalPage: tabs.length
        })
        this.stopLoading()
    }

    // 滚动加载更多发送请求
    getRecommend = async (rid) => {
        try {
            const { data } = await channelApi.getRecommend({
                rid
            })
            if (Array.isArray(data)) {
                const { modules, currentModules, totalPage, currentPage } = this.state
                this.setState({
                    currentModules: [
                        ...currentModules,
                        {
                            title: modules[currentPage].title,
                            tid: modules[currentPage].tid,
                            data: data.slice(0, 4)
                        }
                    ]
                })
                if (currentPage === totalPage - 1) {
                    this.complete()
                }                
            }
        } catch (error) {
            console.log(error)           
        } finally {
            this.stopLoading()
        }
    }    

    // 页面初始化获取频道下面的其他子频道数据
    initChannel = async () => {
        const { modules, currentPage } = this.state
        const { match: { params: { id, childId } } } = this.props
        const results = modules.map(async (mod, index) => {
            let response = null
            if (index === 0) {
                response = await channelApi.getRecommend({
                    rid: childId
                })
            } else {
                response = await channelApi.getDynamic({
                    id: id,
                    rid: childId,
                    pn: currentPage
                })
            }
            return response
        })

        // 按次序输出
        let currentModules = []
        let totalPage = null
        for (const [index, result] of results.entries()) {
            const res = await result
            let cm = {
                title: modules[index].title,
                tid: modules[index].tid,
                data: null
            }
            if (res) {
                // 请求成功解析数据
                const { code, data } = res
                if (code !== 0) { 
                    continue
                }
                if (index === 0) {
                    if (Array.isArray(data)) {
                        cm.data = data.slice(0, 4)                    
                    }
                } else {
                    const { archives, page: { size, count } } = data
                    cm.data = archives
                    totalPage === null && (totalPage = Math.ceil(count / size))
                }                                              
            }
            currentModules.push(cm)
        }

        this.setState({
            currentModules,
            totalPage
        })
        this.stopLoading()
    }

    // 滚动加载更多发送请求
    getChannel = async () => {
        try {
            const { currentPage, totalPage, currentModules } = this.state
            const { match: { params: { id, childId } } } = this.props
            const { data } = await channelApi.getDynamic({
                id: id,
                rid: childId,
                pn: currentPage
            })  
            if (data) {
                const { archives, page: { count, size } } = data
                if (!totalPage) {
                    this.setState({
                        totalPage: Math.ceil(count / size)
                    })
                }
                const newModules = JSON.parse(JSON.stringify(currentModules))
                archives.forEach(item => {
                    const { bvid } = item
                    const match = newModules[1].data.find(item => item.bvid === bvid)
                    if (!match) {
                        newModules[1].data.push(item)
                    }
                })
                this.setState({
                    currentModules: newModules
                })
                if (currentPage === 4) {
                    this.complete()
                }
            }
        } catch (error) {
            console.log(error)          
        } finally {
            this.stopLoading()
        }
    }

    stopLoading = () => {
        this.listRef?.current?.stopLoading()
    }

    startLoading = () => {
        this.listRef?.current?.startLoading()
    }

    complete = () => {
        this.listRef?.current?.complete()
    }

    // 处理页面滚动到底部事件
    onReachEnd = () => {
        const { currentPage, totalPage, isChannelIndex, modules } = this.state
        if (currentPage < totalPage - 1) {
            const nextPage = currentPage + 1
            this.setState({
                currentPage: nextPage
            })
            if (isChannelIndex) {
                this.getRecommend(modules[nextPage].tid)
            } else {
                if (modules[1].data !== null) {
                    this.getChannel()
                }
            }
        } else {
            this.complete()
        }
    }

    // 渲染卡片头部右侧内容
    renderExtra = (index, rowData) => {
        const { isChannelIndex } = this.state
        if (!isChannelIndex) {
            return null
        }
        if ((index - 0) === 0) {
            return (
                <span className={`${css['card-extra']} ${css['card-hot']}`} onClick={() => this.handleRank(rowData.tid)}><i className="fa fa-hot"></i> 排行榜 <i className="fa fa-dropright"></i></span>
            )
        } else {
            return (
                <span className={css['card-extra']} onClick={() => this.handleMore(rowData.tid)}>查看更多 <i className="fa fa-dropright"></i></span>
            )
        }
    }

    handleRank = id => {
        this.props.history.push(`/rank/${id}`)
        
    }

    handleMore = id => {
        const { location: { pathname } } = this.props
        this.props.history.push(`${pathname}/${id}`)
    }

    // 渲染卡片内容
    onRender = (rowData, sectionID, rowId) => {
        const { title, data } = rowData 
        return (
            <>
                <WingBlank key={rowId} size="sm">
                    <Card className={css['card']}>
                        <Card.Header 
                            className={css['card-header']}
                            title={title} 
                            extra={this.renderExtra(rowId, rowData)}
                        ></Card.Header>
                        <Card.Body className={css['card-body']}>
                            {                            
                                Array.isArray(data) ? data.map(item => {                                    
                                    return (
                                        <Cover 
                                            key={item.bvid}
                                            {...item}
                                            play={item.stat ? item.stat.view : item.play} 
                                            danmaku={item.stat ? item.stat.danmaku : item.video_review}                                             
                                        />)
                                }) : ''
                            }
                        </Card.Body>
                    </Card>
                </WingBlank>
                <WhiteSpace size="lg" />
            </>
        )
    }

    componentDidMount() {
        if (this.checkUrl()) {
            this.initData()
        } else {
            this.props.history.replace('/404')
        }                
    }

    componentDidUpdate(prevProps) {
        const prevParams = JSON.stringify(prevProps.match.params)
        const currentParams = JSON.stringify(this.props.match.params)
        if (prevParams !== currentParams) {
            if (this.checkUrl()) {
                this.setState(this.initState(), () => {
                    this.startLoading()
                    this.initData()
                })
            } else {
                this.props.history.replace('/404')
            }                          
        }  
    }

    render() {
        const { currentTab, tabs, currentModules } = this.state
        return (
            <>
                <MenuBar 
                    tabs={tabs} 
                    currentTab={currentTab} 
                    onTabClick={this.handleTab} 
                />

                <LoadMore                    
                    ref={this.listRef}
                    data={currentModules} 
                    pageSize={2}
                    enableRefresh={false}
                    onReachEnd={this.onReachEnd} 
                    renderRow={this.onRender}
                />
            </>
        )
    }
}
